<!--
 * @Author: 宋绍华
 * @Date: 2024-11-12 14:58:02
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-13 16:46:29
 * @FilePath: \sr_system_manager_ui\src\views\project\components\MyProject\ProjectDoc.vue
 * @Description: 项目成员
-->
<template>
  <div :class="[props.mode === 'add' ? 'px-20px' : '']">
    <div class="mb-16px flex justify-between">
      <div class="color-#86909C text-14px mt-17px " v-if="props.showTips">
        <span
          v-if="props.projectNature !== projectNatureEnum.projectNatureHorizontal">*立项时请上传盖章的立项通知书、红头文件、盖章的申报书、合同委托书等相关材料.</span>
        <span v-else>*立项时请上传合同书、项目组成员等相关材料.</span>
      </div>
      <FileUpload :modelValue="tempList" :class="[props.mode === 'add' ? 'mt-10px' : 'mt-[-32px]']" v-if="props.mode !== 'view'"
        :disabled="tableData.length >= 20" :showList="false" :isShowTip="false" :limit="20000"
        @update:modelValue="update" :file-size="100" />
    </div>
    <el-table border v-loading="loading" :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="序号" width="48">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="文件名">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="uploadTime" label="上传时间" />
      <el-table-column prop="option" label="操作">
        <template #default="scope">
          <el-button type="primary" @click="previewUrl(scope.row?.attachmentFileInfoDTO?.url)" link>查看</el-button>
          <el-button @click="onDelete(scope.row)" v-if="props.mode !== 'view' && scope.row.isDelete" type="danger"
            link>删除</el-button>
          <el-button v-else type="primary" link @click="download(scope.row?.attachmentFileInfoDTO)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { DocCreateApi, projectDocumentDeleteApi, projectDocumentListDetailApi } from '@/api/project';
import { BaseSuccessRespDTO } from '@/api/project/types';
import { projectNatureEnum } from '@/utils/constEnum';

const props = defineProps({
  mode: {
    type: String as PropType<'add' | 'edit' | 'view'>,
    default: 'add'
  },
  projectId: {
    type: String,
    default: ''
  },
  projectNature: {
    type: Number,
    default: 1
  },
  showTips: {
    type: Boolean,
    default: true
  }
})

const { proxy } = getCurrentInstance()
const tableData = ref([])
const route = useRoute()
const tempList = ref([])

// 创建文档
const { runAsync: coCreate } = useRequest(DocCreateApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    return res.isSuccess
  }
})

// 获取详情
const { runAsync: projectDocumentListDetail } = useRequest(projectDocumentListDetailApi, {
  manual: true,
  onSuccess: (res) => {
    tableData.value = res?.map(i => {
      return {
        ...i,
        name: i.attachmentFileInfoDTO?.name,
      }
    })
  }
})

// 删除文档行
const { runAsync: projectDocumentDelete, loading } = useRequest(projectDocumentDeleteApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage.success('删除成功！')
      projectDocumentListDetail({ projectId: props.projectId })
    }
  }
})

const update = async (list: any) => {
  // list 包含之前上传的文件
  // tableData 当前存在的文件
  const ids = list.filter(i => !tableData.value.map(i => i.fileId).includes(i.id))?.map(i => i.id)
  // 临时文件存储
  tempList.value = list
  const fileIds = [...ids]
  await coCreate({ fileIds, projectId: props.projectId, isTemp: false })
  projectDocumentListDetail({ projectId: props.projectId })
}

const onDelete = (row) => {
  // 过滤掉删掉的文件
  tempList.value = tempList.value.filter(i => i.id !== row.fileId)
  projectDocumentDelete({ id: row.id })
}


// 预览
const previewUrl = (url) => {
  proxy.$preview.open({
    src: url,
  })
}

const download = (file) => {
  proxy.$download.downloadFileSync(file?.url, file?.name)
}

watch(
  () => [props.mode, props.projectId],
  val => {
    if (props.mode !== 'add' || props.projectId) {
      projectDocumentListDetail({ projectId: props.projectId || route.query.projectId })
    }
  },
  {
    immediate: true
  }
)

const validate = () => {
  return tableData.value.some(i => {
    const isEmpty = Object.keys(i).some(key => {
      if (i[key] === undefined) {
        return false
      }
      return true
    })

    return isEmpty
  })
}


// 创建项目
const create = async (isTemp: boolean = false) => {
  // 暂存
  if (isTemp) {
    ElMessage({
      message: '暂存成功',
      type: 'success',
    })
    return true
  }

  // 数据为空，可以直接放过去
  // if (tableData.value.length === 0) return true
  const res = await validate()
  if (!res) {
    ElMessage.error('请完善内容')
    return false
  }

  return true
}

defineExpose({
  create
})
</script>

<style scoped lang="scss">
:deep(.upload-file-uploader) {
  margin-bottom: 0;
}
</style>